package book;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import state.Fen;
import state.GameState;

public class Book2 {

	// The book I am using  is from Colin Frayn's Beowulf project
	// http://www.frayn.net/beowulf/index.html
	
	//It looks like a line of FEN followed by a line containing several move choices
	
	//   rnbq1rk1/pp3ppp/2pb4/3p4/2PPn3/3B1N2/PP3PPP/RNBQ1RK1 w - -
	//   f1e1{5} d1c2{6}
	

	public static Map<Long,List<String>> bookMoves = new HashMap<Long, List<String>>();
	
	public Book2(String fileName) {
		createBook(fileName);
	}
	
	public String getMove(GameState gs) {
		String fen = Fen.toFEN(gs);
    	
     	GameState state2= new GameState(fen);
    	Long key = new Long(state2.getHash());
    	
		if (bookMoves.containsKey(key)) {
			  List<String> moveList = bookMoves.get(key);
			  return randomMove(moveList);
		}
		else {
			return null;
		}
	}
	private String randomMove(List<String> moveList) {
		
		int i = (int) (Math.random() *  ( moveList.size() - 1 ));
		return moveList.get(i);
	}

	public void createBook(String fileName) {
		
	   InputStream inputStream = getClass().getResourceAsStream(fileName);
	   if(inputStream == null)
		try {
			throw new FileNotFoundException();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	        
	   BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
	        
		String line = null;
		boolean isFen=true;
		String delims = "[{ }]+";
		
		try {
			Long hash=null;
			while ((line = br.readLine()) != null) {
			   // System.out.println(line);
			    if (line.equals("#END#")) break;
			   
			    if (isFen) {
			    	GameState gs = new GameState(line);
			    	hash = gs.getHash();
			    	isFen=false;
			    }
			    else {
			    	String[] tokens = line.split("\\s+");
			    	List<String> moveList = new ArrayList<String>();
			    	for (int i=0; i < tokens.length; i++) {
			    		//System.out.println("token " + tokens[i]);
			    		String[] tokens2 = tokens[i].split(delims);
			    		String move = tokens2[0];
			    	
			    		moveList.add(move);
			    	}
			    	bookMoves.put(hash, moveList);
			    	isFen=true;
			    }
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("Finished");
	}
	
}
